package com.industrial.premu.service.impl.sqsj;

import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;

import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.utils.StringUtils;
import com.industrial.common.core.utils.poi.ExcelUtil;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.premu.domain.PreMuCompanyInfo;
import com.industrial.premu.domain.SysOperError;
import com.industrial.premu.domain.sqsj.PreMuImportBenefitEvaluationNo;
import com.industrial.premu.domain.sqsj.PreMuImportLog;
import com.industrial.premu.domain.sqsj.PreMuImportShuiwu;
import com.industrial.premu.mapper.PreMuCompanyInfoMapper;
import com.industrial.premu.mapper.PreMuCompanyInfoNoMapper;
import com.industrial.premu.mapper.SysOperErrorMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportBenefitEvaluationNoMapper;
import com.industrial.premu.mapper.sqsj.PreMuImportLogMapper;
import com.industrial.premu.service.IPreMuImportBenefitEvaluationNoService;
import com.industrial.premu.service.IPreMuImportLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;


/**
 * 亩产效益评价导入(不参评企业)Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-25
 */
@Service
public class PreMuImportBenefitEvaluationNoServiceImpl implements IPreMuImportBenefitEvaluationNoService
{
    @Autowired
    private PreMuImportBenefitEvaluationNoMapper preMuImportBenefitEvaluationNoMapper;
    private static final Pattern numberPattern = Pattern.compile("^\\d+(\\.\\d+)?$");

    private static final int BATCH_SIZE = 300;

    @Autowired
    private SysOperErrorMapper sysOperErrorMapper;

    @Autowired
    private PreMuCompanyInfoMapper preMuCompanyInfoMapper;
    @Autowired
    private PreMuCompanyInfoNoMapper preMuCompanyInfoNoMapper;

    /**
     * 查询亩产效益评价导入(不参评企业)
     *
     * @param id 亩产效益评价导入(不参评企业)主键
     * @return 亩产效益评价导入(不参评企业)
     */
    @Override
    public PreMuImportBenefitEvaluationNo selectPreMuImportBenefitEvaluationNoById(String id)
    {
        return preMuImportBenefitEvaluationNoMapper.selectPreMuImportBenefitEvaluationNoById(id);
    }

    /**
     * 查询亩产效益评价导入(不参评企业)列表
     *
     * @param preMuImportBenefitEvaluationNo 亩产效益评价导入(不参评企业)
     * @return 亩产效益评价导入(不参评企业)
     */
    @Override
    public List<PreMuImportBenefitEvaluationNo> selectPreMuImportBenefitEvaluationNoList(PreMuImportBenefitEvaluationNo preMuImportBenefitEvaluationNo)
    {
        preMuImportBenefitEvaluationNo.setDelFlag("0");
        return preMuImportBenefitEvaluationNoMapper.selectPreMuImportBenefitEvaluationNoList(preMuImportBenefitEvaluationNo);
    }

    /**
     * 新增亩产效益评价导入(不参评企业)
     *
     * @param preMuImportBenefitEvaluationNo 亩产效益评价导入(不参评企业)
     * @return 结果
     */
    @Override
    public int insertPreMuImportBenefitEvaluationNo(PreMuImportBenefitEvaluationNo preMuImportBenefitEvaluationNo)
    {
        return preMuImportBenefitEvaluationNoMapper.insertPreMuImportBenefitEvaluationNo(preMuImportBenefitEvaluationNo);
    }

    /**
     * 修改亩产效益评价导入(不参评企业)
     *
     * @param preMuImportBenefitEvaluationNo 亩产效益评价导入(不参评企业)
     * @return 结果
     */
    @Override
    public int updatePreMuImportBenefitEvaluationNo(PreMuImportBenefitEvaluationNo preMuImportBenefitEvaluationNo)
    {
        return preMuImportBenefitEvaluationNoMapper.updatePreMuImportBenefitEvaluationNo(preMuImportBenefitEvaluationNo);
    }

    /**
     * 批量删除亩产效益评价导入(不参评企业)
     *
     * @param ids 需要删除的亩产效益评价导入(不参评企业)主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportBenefitEvaluationNoByIds(String[] ids)
    {
        return preMuImportBenefitEvaluationNoMapper.deletePreMuImportBenefitEvaluationNoByIds(ids);
    }

    /**
     * 删除亩产效益评价导入(不参评企业)信息
     *
     * @param id 亩产效益评价导入(不参评企业)主键
     * @return 结果
     */
    @Override
    public int deletePreMuImportBenefitEvaluationNoById(String id)
    {
        return preMuImportBenefitEvaluationNoMapper.deletePreMuImportBenefitEvaluationNoById(id);
    }
    @Autowired
    private PreMuImportLogMapper preMuImportLogMapper;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void removeData(PreMuImportBenefitEvaluationNo params,String deptCode) {
        preMuImportBenefitEvaluationNoMapper.removeData(params);
        PreMuImportLog removeParams = new PreMuImportLog();
        removeParams.setYear(String.valueOf(params.getYear()));
        removeParams.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
        removeParams.setDeptCode(deptCode);
        preMuImportLogMapper.removeData(removeParams);
    }

    @Override
    public AjaxResult importBenefitEvaluationNoExcelData(String year, String companyType, MultipartFile file) {
        try{
            ExcelUtil<PreMuImportBenefitEvaluationNo> util = new ExcelUtil<PreMuImportBenefitEvaluationNo>(PreMuImportBenefitEvaluationNo.class);
            List<PreMuImportBenefitEvaluationNo> preMuImportBenefitEvaluationNos = util.importExcel(file.getInputStream());
            if (StringUtils.isNull(preMuImportBenefitEvaluationNos) || preMuImportBenefitEvaluationNos.isEmpty()) {
                return AjaxResult.warn("导入数据不能为空");
            }

            //前置检查
            StringBuilder errorInfo = new StringBuilder("<h3><b>以下企业类型与您导入时所选企业类型不符:</b></h3>");
            int errorCount = 1;

            for(PreMuImportBenefitEvaluationNo t : preMuImportBenefitEvaluationNos){
                if(!StringUtils.equals(t.getCompanyType(), companyType)){
                    errorInfo.append("<font color='red'>").append(String.format("%d、",errorCount)).append(t.getCompanyName()).append("</font><br/>");
                    errorCount++;
                }
            }
            if(errorCount != 1){
                return AjaxResult.warn(errorInfo.toString());
            }
            List<PreMuImportBenefitEvaluationNo> realList = new ArrayList<PreMuImportBenefitEvaluationNo>();
            int successNum = 0;
            int updateNum = 0;
            int failureNum = 0;

            StringBuilder failureMsg = new StringBuilder();
            StringBuilder allMsg = new StringBuilder();

            //批处理用
            List<String> usccList = new ArrayList<String>();
            List<PreMuImportBenefitEvaluationNo> mcImportExistList = new ArrayList<PreMuImportBenefitEvaluationNo>();
            Map<String,String> mcImportExistMap = new HashMap<String,String>();

            List<PreMuImportBenefitEvaluationNo> addImportList = new ArrayList<PreMuImportBenefitEvaluationNo>();
            List<PreMuImportBenefitEvaluationNo> updateImportList = new ArrayList<PreMuImportBenefitEvaluationNo>();
            List<PreMuCompanyInfo> updateCompanyList=new ArrayList<>();
            if (preMuImportBenefitEvaluationNos != null && !preMuImportBenefitEvaluationNos.isEmpty()) {
                for(int i=0;i<preMuImportBenefitEvaluationNos.size();i++){
                    PreMuImportBenefitEvaluationNo data = preMuImportBenefitEvaluationNos.get(i);
                    if (data.getUscc() != null && !"".equals(data.getUscc())){
                        usccList.add(data.getUscc().trim());
                        realList.add(data);
                        if("1".equals(data.getCompanyType())){

                            if(data.getMainIncome() == null) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->营业收入为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }

                            String totalUsed = data.getTotalUsed();
                            BigDecimal totalUsedBigDecimal = StringUtils.isBlank(totalUsed) ? BigDecimal.ZERO : new BigDecimal(totalUsed);

                            if(totalUsedBigDecimal.compareTo(BigDecimal.ZERO) < 0) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->总耗能为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                            if(data.getRdFunds() == null) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->研发经费支出为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                            if(data.getTotalEquivalent() == null) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->排放总当量为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                            if(data.getIndustryOutput() == null) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->工业总产值为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                            if(data.getAnnualEmployees() == null || data.getAnnualEmployees() < 0L) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->年平均职工人数为空或异常，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                            if(data.getProfitTotal() == null) {
                                Map<String,String> result = new HashMap<>();
                                result.put("allMsg",data.getCompanyName()+"->利润总额为空，请检查导入数据！");
                                return AjaxResult.error("导入失败",result);
                            }
                        }
                    }

                    //将行业代码保存至list容器中，以便同步企业信息表
//                    PreMuCompanyInfo companyInfoDO=new PreMuCompanyInfo();
//                    companyInfoDO.setUscc(data.getUscc());
//                    companyInfoDO.setIndustryType(data.getIndustryType());
//                    companyInfoDO.setIndustryMediumType(data.getIndustryMediumType());
//                    companyInfoDO.setCompanyScale(data.getCompanyScale());
//                    updateCompanyList.add(companyInfoDO);
                }
            }
            long count = usccList.stream().distinct().count();
            boolean isRepeat = count < usccList.size();
            if (isRepeat) {
                Map<String,String> result = new HashMap<>();
                result.put("allMsg","有重复统一社会信用代码，请检查导入数据！");
                return AjaxResult.error("导入失败",result);
            }
            mcImportExistList = preMuImportBenefitEvaluationNoMapper.getImportBenefitEvaluationExistList(year, usccList);
            if(mcImportExistList != null) {
                mcImportExistList.forEach(data ->{
                    mcImportExistMap.put(data.getUscc(),data.getId());
                });
            }

            int travel = 1;

            for (int i = 0; i < preMuImportBenefitEvaluationNos.size(); i++) {
                travel++;
                PreMuImportBenefitEvaluationNo mcImportBenefitEvaluationDO = preMuImportBenefitEvaluationNos.get(i);
                mcImportBenefitEvaluationDO.setYear(Long.valueOf(year));
                mcImportBenefitEvaluationDO.setCounty(SecurityUtils.getLoginUser().getSysUser().getDistrict());
                mcImportBenefitEvaluationDO.setStatus("0");
                String uscc = mcImportBenefitEvaluationDO.getUscc();
                if (uscc == null || "".equals(uscc) || year == null || "".equals(year)) {
                    continue;
                } else {
                    uscc = uscc.trim();
                }
                if (mcImportBenefitEvaluationDO.getSumArea() == null || !numberPattern.matcher(mcImportBenefitEvaluationDO.getSumArea() + "").matches() || Double.valueOf(mcImportBenefitEvaluationDO.getSumArea()) == 0) {
                    BigDecimal userArea = new BigDecimal(0);
                    BigDecimal otherArea = new BigDecimal(0);
                    BigDecimal leasedArea = new BigDecimal(0);
                    BigDecimal rentOutArea = new BigDecimal(0);
                    BigDecimal sumArea = new BigDecimal(0);

                    if(mcImportBenefitEvaluationDO.getUseArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getUseArea()+"").matches()){
                        userArea = new BigDecimal(mcImportBenefitEvaluationDO.getUseArea()+"");
                    }
                    if(mcImportBenefitEvaluationDO.getOtherArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getOtherArea()+"").matches()){
                        otherArea = new BigDecimal(mcImportBenefitEvaluationDO.getOtherArea()+"");
                    }
                    if(mcImportBenefitEvaluationDO.getLeasedArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getLeasedArea()+"").matches()){
                        leasedArea = new BigDecimal(mcImportBenefitEvaluationDO.getLeasedArea()+"");
                    }
                    if(mcImportBenefitEvaluationDO.getRentOutArea() != null && numberPattern.matcher(mcImportBenefitEvaluationDO.getRentOutArea()+"").matches()){
                        rentOutArea = new BigDecimal(mcImportBenefitEvaluationDO.getRentOutArea()+"");
                    }
                    sumArea = userArea.add(otherArea).add(leasedArea).subtract(rentOutArea);
                    if(sumArea.doubleValue()==0){
                        Map<String,String> result = new HashMap<>();
                        result.put("allMsg","计算后用地面积不可为0，请检查导入数据！");
                        return AjaxResult.error("导入失败",result);
                    }
                    mcImportBenefitEvaluationDO.setSumArea(sumArea.toString());
                }
                if (mcImportExistMap!= null && mcImportExistMap.containsKey(uscc)) {
                    mcImportBenefitEvaluationDO.setId(mcImportExistMap.get(uscc));
                    mcImportBenefitEvaluationDO.setDelFlag("0");
                    updateImportList.add(mcImportBenefitEvaluationDO);
                } else {
                    mcImportBenefitEvaluationDO.setId(IdUtil.simpleUUID());
                    mcImportBenefitEvaluationDO.setCreateDate(DateUtils.getNowDate());
                    mcImportBenefitEvaluationDO.setCreateBy(SecurityUtils.getUserId());
                    mcImportBenefitEvaluationDO.setDelFlag("0");
                    addImportList.add(mcImportBenefitEvaluationDO);
                }

                if (addImportList != null && addImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportBenefitEvaluationNoMapper.batchSave(addImportList);
                    successNum += importNum;
                    addImportList.clear();
                    //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);
                    System.gc();
                }
                if (updateImportList != null && updateImportList.size() >= BATCH_SIZE) {
                    int importNum = preMuImportBenefitEvaluationNoMapper.batchUpdateByUscc(year, updateImportList);
                    successNum += importNum;
                    updateNum += importNum;
                    updateImportList.clear();
                    //preMuCompanyInfoMapper.batchUpdateByUscc(updateCompanyList);
                    System.gc();
                }
            }
            if (addImportList != null && !addImportList.isEmpty()) {

                int importNum = preMuImportBenefitEvaluationNoMapper.batchSave(addImportList);
                successNum += importNum;
                addImportList.clear();
                //preMuCompanyInfoNoMapper.batchUpdateByUscc(updateCompanyList);
                System.gc();
            }
            if (updateImportList != null && !updateImportList.isEmpty()) {

                int importNum = preMuImportBenefitEvaluationNoMapper.batchUpdateByUscc(year, updateImportList);
                successNum += importNum;
                updateNum += importNum;
                updateImportList.clear();
                //preMuCompanyInfoNoMapper.batchUpdateByUscc(updateCompanyList);
                System.gc();
            }
            if (successNum > 0) {
                allMsg.insert(0, "恭喜您，共" + successNum + " 条数据导入成功！");
            }
            Map<String,String> result = new HashMap<>();
            result.put("sum",String.valueOf(successNum));
            result.put("updateNum",String.valueOf(updateNum));
            result.put("msg",allMsg.toString());
            result.put("allMsg",allMsg.toString());
            return AjaxResult.success(result);
        }catch (Exception e){
            String requestURI = "/industrial-premu/importExcelData";
            SysOperError sysOperError = new SysOperError();
            sysOperError.setBaseId(IdUtil.simpleUUID());
            sysOperError.setBaseCreateTime(new Date());
            sysOperError.setErrorMsg(e.getMessage());
            sysOperError.setUrlAddress(requestURI);
            sysOperError.setOperId(SecurityUtils.getUserId());
            sysOperErrorMapper.saveErrorInfo(sysOperError);
            return AjaxResult.error("导入失败");
        }
    }
}